package com.universalInterface.lims_interface.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.universalInterface.common.exception.BusinessException;
import com.universalInterface.lims_interface.common.constants.CodeRuleConstant;
import com.universalInterface.lims_interface.common.utils.CodeRuleUtil;
import com.universalInterface.lims_interface.entity.LabInfo;
import com.universalInterface.lims_interface.mapper.LabInfoMapper;
import com.universalInterface.lims_interface.service.ILabInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 实验室信息
 * </p>
 *
 * @author author
 * @since 2023-12-19
 */
@RequiredArgsConstructor
@Service
public class LabInfoServiceImpl implements ILabInfoService {

	private final LabInfoMapper labInfoMapper;

	private final RedisTemplate redisTemplate;

	@Override
	public LabInfo save(LabInfo entity) {
		// 查询实验室名称是否重复
		QueryWrapper q = new QueryWrapper();
		q.eq("lab_name", entity.getLabName());
		LabInfo labInfo = labInfoMapper.selectOne(q);
		if (labInfo != null) {
			throw new BusinessException(500, "实验室名称重复");
		}
		entity.setLabGuid(IdUtil.getSnowflakeNextId());
		Integer o = (Integer) redisTemplate.opsForValue().get(CodeRuleConstant.LAB_INFO_NO);
		if (o != null && o >= 0) {
			entity.setLabNum(CodeRuleUtil.getAutoIncrementNo(CodeRuleConstant.LAB_INFO_CODE_PREFIX, o));
		} else {
			o = 0;
			entity.setLabNum(CodeRuleUtil.getAutoIncrementNo(CodeRuleConstant.LAB_INFO_CODE_PREFIX, 0));
		}
		int i = labInfoMapper.insert(entity);
		if (i > 0) {
			redisTemplate.opsForValue().set(CodeRuleConstant.LAB_INFO_NO, ++o);
		}
		return entity;
	}

	@Override
	public Integer updateById(LabInfo entity) {
		// 不允许更新labGuid值
		if (entity.getLabGuid() != null) {
			throw new BusinessException(500, "不允许更新labGuid值");
		}
		// 查询实验室名称是否重复
		QueryWrapper q = new QueryWrapper();
		q.eq("lab_name", entity.getLabName());
		LabInfo labInfo = labInfoMapper.selectOne(q);
		if (labInfo != null) {
			throw new BusinessException(500, "实验室名称重复");
		}
		return labInfoMapper.updateById(entity);
	}

	@Override
	public Integer deleteById(Long id) {
		return labInfoMapper.deleteById(id);
	}

	@Override
	public LabInfo get(LabInfo entity) {
		QueryWrapper q = new QueryWrapper();
		if (entity.getLabGuid() != null) {
			q.eq("lab_guid", entity.getLabGuid());
		}
		if (StrUtil.isNotBlank(entity.getLabNum())) {
			q.eq("lab_num", entity.getLabNum());
		}
		if (StrUtil.isNotBlank(entity.getLabName())) {
			q.eq("lab_name", entity.getLabName());
		}
		if (q.isEmptyOfWhere()) {
			return null;
		}
		LabInfo labInfo = labInfoMapper.selectOne(q);
		return labInfo;
	}

}
